<?php
/**
 * Introduction: 图像处理
 * User: 杨陈鹏
 * Date: 15/12/13
 * Time: 上午10:20
 * Last date: 15/12/13 上午10:20
 * Last user: arpeng
 */

namespace Files\Controller;


use Think\Controller;

class ImageController extends Controller
{
    public function index()
    {
        $this->doImage();
    }

    /**
     * 处理图像
     * @param $file 图像地址
     */
    public function doImage($file = false)
    {
        /**
         * 读取文件路径，判断是否允许读取源文件
         */
        header('Content-Type: text/html; charset=utf-8');

        ini_set("memory_limit", "1024M");
        $conf = C('IMAGE_CONFIG');//加载配置
        /**
         * 获取原图信息以及缩略图尺寸
         */
        $file = $file ? $file : I('get.file');
        if (empty($file)) {
            //GET 参数为空时返回 404
            die('404 File not found');
        }
        $file_name = $file;
        if (preg_match("/(.*)_(.*)_(.*)\.(.*)/", $file, $v) === 1) {
            //读取缩略图配置
            $file_name = $v[1] . '.' . $v[4];
        }
        foreach (explode('/', dirname($file)) as $r) {
            if (!empty($r)) {
                $dir_name = $r;
                break;
            }
        }
        $file_path_info = pathinfo($file_name);
        if (!is_file($file_name)) {
            $file_name = $file_path_info['dirname'] . '/' . $conf['original'] . $file_path_info['basename'];
            if (!is_file($file_name)) {
                die('404 File not found');
            }
        }
        /**
         * 获取原图信息以及缩略图尺寸结束
         */
        /**
         * 初始化配置
         */
        $is_thumb = false;
        $is_watermark = false;
        $watermark_pos = 3;
        $watermark_w = 500;
        $watermark_h = 500;
        $watermark_src = '';
        if (!isset($conf['dir_lists'][$dir_name])) {
            die('No configuration information in the current directory');
        }
        isset($conf['dir_lists'][$dir_name]['thumb']) && $is_thumb = $conf['dir_lists'][$dir_name]['thumb'];//
        isset($conf['dir_lists'][$dir_name]['watermark']) && $is_watermark = $conf['dir_lists'][$dir_name]['watermark'];
        isset($conf['dir_lists'][$dir_name]['watermark_pos']) && $watermark_pos = $conf['dir_lists'][$dir_name]['watermark_pos'];
        isset($conf['dir_lists'][$dir_name]['watermark_w']) && $watermark_w = $conf['dir_lists'][$dir_name]['watermark_w'];
        isset($conf['dir_lists'][$dir_name]['watermark_h']) && $watermark_h = $conf['dir_lists'][$dir_name]['watermark_h'];
        isset($conf['dir_lists'][$dir_name]['watermark_src']) && $watermark_src = $conf['dir_lists'][$dir_name]['watermark_src'];
        if (!isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]])) {
            die('The current thumbnail size no configuration information');
        }
        isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['thumb']) && $is_thumb = $conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['thumb'];
        isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark']) && $is_watermark = $conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark'];
        isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_pos']) && $watermark_pos = $conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_pos'];
        isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_w']) && $watermark_w = $conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_w'];
        isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_h']) && $watermark_h = $conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_h'];
        isset($conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_src']) && $watermark_src = $conf['dir_lists'][$dir_name]['wh_lists'][$v[2] . '_' . $v[3]]['watermark_src'];
        /**
         * 初始化配置结束
         */
        if ($is_thumb == false) {
            die('In the current directory does not allow to create thumbnails');//不允许生成缩略图
        }
        /**
         * 读取源文件，尺寸如果小于缩略图尺寸则不加水印
         */
        if (($is_watermark === true)) {
            $source_info = getimagesize($file_name);
            $source_width = $source_info[0];
            $source_height = $source_info[1];
            if ($source_width < $watermark_w || $source_height < $watermark_h) {
                $is_watermark = false;
            }
            /*
        if ($v[3] == 0 && $v[2] != 0) {
        //    $v[3] = $source_height * ($v[2] / $source_width);
        } elseif ($v[2] == 0 && $v[3] != 0) {
        //     $v[2] = $source_width * ($v[3] / $source_height);
        }
         *
         */
        }
        /**
         * 判断水印是否存在，以及缩略图尺寸是否符合最小缩略图要求尺寸
         */
        if (is_numeric($v[2]) && is_numeric($v[3])) {
            if ($is_watermark == true) {
                if ($v[2] < $watermark_w || $v[3] < $watermark_h) {
                    //判断缩略图尺寸如果小于水印最小尺寸则不加水印
                    $is_watermark = false;
                } else {
                    if (!is_file($watermark_src)) {
                        die('Watermark 404 File not found');
                    }
                }
            }
            $this->imagecropper($file_name, $v[2], $v[3], $is_watermark, $watermark_pos, $watermark_src, $conf['original']);
        } else {
            die('Parameter error');
        }
    }

    /**
     *
     * @param string $source_path 原图路径
     * @param int $target_width 目标宽度
     * @param int $target_height 目标高度
     * @param  boolean $watermark 是否加水印
     * @param string $watermark_pos 水印路径
     */
    public function imagecropper($source_path, $target_width, $target_height, $watermark = false, $watermark_pos = 0, $watermark_src = '', $original)
    {

        $source_info = getimagesize($source_path);
        $source_width = $source_info[0];
        $source_height = $source_info[1];
        $source_mime = $source_info['mime'];
        $source_ratio = $source_height / $source_width;

        $pathinfo = pathinfo($source_path);//原图信息
        $dst_file = $pathinfo['dirname'] . '/' . str_replace($original, '', $pathinfo['filename']) . '_' . $target_width . '_' . $target_height . '.' . $pathinfo['extension'];//图像输出地址

        if ($target_height == 0 && $target_width != 0) {
            $target_height = $source_height * ($target_width / $source_width);
        }
        if ($target_width == 0 && $target_height != 0) {
            $target_width = $source_width * ($target_height / $source_height);
        }
        $target_ratio = $target_height / $target_width;

        $cropped_width = $source_width;
        $cropped_height = $source_height;
        // 源图过高
        if ($source_ratio > $target_ratio) {
            $cropped_width = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            //   $source_y = ($source_height - $cropped_height) / 2;
            $source_y = 0;
            // 源图过宽
        } elseif ($source_ratio < $target_ratio) {
            $cropped_width = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
            // 源图适中
        } else {
            $cropped_width = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }
        /**
         * 判断原图格式
         */
        switch ($source_mime) {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }

        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
        $target_width = $cropped_width > $target_width ? $target_width : $cropped_width;
        $target_height = $cropped_height > $target_height ? $target_height : $cropped_height;

        // 设置背景
        $target_image = imagecreatetruecolor($target_width, $target_height);

        imagealphablending($target_image, true);
        imagesavealpha($target_image, true);
        imagealphablending($cropped_image, false);
        imagesavealpha($cropped_image, true);
        // 裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);

        /**
         * 添加水印
         */
        if ($watermark === true) {
            $water_info = getimagesize($watermark_src);
            $water_w = $water_info[0];//取得水印图片的宽
            $water_h = $water_info[1];//取得水印图片的高
            switch ($water_info[2]) {
                //取得水印图片的格式
                case 1:
                    $water_im = imagecreatefromgif($watermark_src);
                    break;
                case 2:
                    $water_im = imagecreatefromjpeg($watermark_src);
                    break;
                case 3:
                    $water_im = imagecreatefrompng($watermark_src);
                    break;
                default:
                    die('Watermark file format is not correct, only support GIF, JPG, PNG');
            }
            switch ($watermark_pos) {
                case 1://1为顶端居左
                    $posX = 0;
                    $posY = 0;
                    break;
                case 2://2为顶端居中
                    $posX = ($target_width - $water_w) / 2;
                    $posY = 0;
                    break;
                case 3://3为顶端居右
                    $posX = $target_width - $water_w;
                    $posY = 0;
                    break;
                case 4://4为中部居左
                    $posX = 0;
                    $posY = ($target_height - $water_h) / 2;
                    break;
                case 5://5为中部居中
                    $posX = ($target_width - $water_w) / 2;
                    $posY = ($target_height - $water_h) / 2;
                    break;
                case 6://6为中部居右
                    $posX = $target_width - $water_w;
                    $posY = ($target_height - $water_h) / 2;
                    break;
                case 7://7为底端居左
                    $posX = 0;
                    $posY = $target_height - $water_h;
                    break;
                case 8://8为底端居中
                    $posX = ($target_width - $water_w) / 2;
                    $posY = $target_height - $water_h;
                    break;
                case 9://9为底端居右
                    $posX = $target_width - $water_w;
                    $posY = $target_height - $water_h;
                    break;
                default://随机
                    $posX = rand(0, ($target_width - $water_w));
                    $posY = rand(0, ($target_height - $water_h));
                    break;
            }

            //      imagealphablending($target_image, true);
            imagecopy($target_image, $water_im, $posX, $posY, 0, 0, $water_w, $water_h);
        }
        /**
         * 添加水印结束
         */
        switch ($source_mime) {
            case 'image/jpeg':
                header('Content-Type: image/jpg');
                imagejpeg($target_image, $dst_file, 100);
                imagejpeg($target_image, null, 100);
                break;
            case 'image/gif':
                header('Content-Type: image/gif');
                imagegif($target_image, $dst_file);
                imagegif($target_image);
                break;
            case 'image/png':
                header('Content-Type: image/png');
                imagepng($target_image, $dst_file);
                imagepng($target_image);
                break;
        }
        imagedestroy($source_image);
        imagedestroy($target_image);
        imagedestroy($cropped_image);
    }

}